<template>
    <div class="app-container">
        <div class="searchAll" slot="search">
            <el-form :model="queryParams" ref="queryForm" label-position="right" v-show="showSearch" label-width="68px">
                <el-row :gutter="20">
                    <el-col :span="6">
                        <el-form-item label="用户组" prop="groupName">
                            <el-input v-model="queryParams.groupName" :placeholder="$t('public.placeholder',{placeholder: '用户组'})" size="small" clearable @keyup.enter.native="handleQuery" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="厂区" prop="factoryName">
                            <el-input v-model="queryParams.factoryName" :placeholder="$t('public.placeholder',{placeholder:'厂区'})" size="small" clearable @keyup.enter.native="handleQuery" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" align="right">
                        <span class="searchAres searchAresHeng">
                            <el-button type="primary" icon="el-icon-search" size="mini" class="searchBtn" @click="handleQuery">{{ $t("public.query") }}</el-button>
                            <el-button class="resectBtn" icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t("public.reset") }}</el-button>
                        </span>
                    </el-col>
                </el-row>
            </el-form>
        </div>
        <div class="tableList">
            <div class="insTitle">
                <span>用户组管理</span>
            </div>
            <div class="btnGroup">
                <el-button v-hasPermi="['ny-iqc:uerGroup:add']" type="primary" icon="el-icon-plus" size="mini" class="additemBtn" @click="handleAdd">{{ $t("public.add") }}</el-button>
                <el-button v-hasPermi="['ny-iqc:uerGroup:edit']" class="importitemBtn" size="mini" @click="handleEdit"><img src="../../../assets/images/icons/edit.png" alt=""> {{ $t("public.edit") }}</el-button>
                <el-button v-hasPermi="['ny-iqc:uerGroup:import']" class="importitemBtn" size="mini" @click="handleImport"><img src="../../../assets/images/icons/daoru.png" alt=""> {{ $t("public.import") }}</el-button>
                <el-button v-hasPermi="['ny-iqc:uerGroup:export']" class="exportitemBtn" size="mini" :loading="exportLoading" @click="handleExport"><img src="../../../assets/images/icons/daochu.png" alt=""> {{ $t("public.export") }}</el-button>
                <el-button icon="el-icon-delete" size="mini" class="deleteitemBtn" @click="handleRemove">{{$t('public.delete')}}</el-button>
            </div>

            <el-table style="margin-top:10px" stripe v-loading="loading" :data="postList" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" align="center" />

                <el-table-column label="用户组名" align="center" prop="groupName" />
                <el-table-column label="厂区" align="center" prop="factoryName" />
                <el-table-column label="负责区域" align="center" prop="territory" />
                <el-table-column label="描述信息" align="center" prop="description" />

                <el-table-column :label="$t('public.opera')" fixed="right" align="center" width="100">
                    <template slot-scope="scope">
                        <div class="action-wrap">
                            <table-body-btn type="gwedit" name="编辑用户" @click.native="handleView(scope.row,2)" v-hasPermi="['ny-iqc:uerGroup:edit']" />
                            <table-body-btn type="gwview" name="查看" @click.native="handleView(scope.row,3)" v-hasPermi="['ny-iqc:uerGroup:getInfo']" />
                            <table-body-btn type="gwdelete" :name="$t('public.delete')" @click.native="handleDelete(scope.row)" v-hasPermi="['ny-iqc:uerGroup:remove']" />
                        </div>
                    </template>
                </el-table-column>
            </el-table>

            <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" layout="total, sizes, prev, pager, next, jumper" />
        </div>
        <detail :visible.sync="detailVisible" v-model="form" :type="dialogType" @refresh="getList()"></detail>
        <drawer :visible.sync="drawerVisible" v-model="form" :type="dialogType" @refresh="getList()"></drawer>
        <!--    <enjoy-user-tree-dialog :visible.sync="userDialogVisible"   title="添加用户" @change="handlerDialogChange"></enjoy-user-tree-dialog>-->
        <!-- 用户导入对话框 -->
        <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
            <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">{{$t('formValidation.dragFilesHere')}}&nbsp;{{$t('formValidation.or')}}<em>{{$t('formValidation.clickToUpload')}}</em></div>
                <div class="el-upload__tip text-center" slot="tip">
                    <div class="el-upload__tip" slot="tip">
                        <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
                    </div>
                    <span>{{$t('formValidation.onlyXlsXlsx')}}</span>
                    <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">{{ $t('formValidation.downloadTemplate') }}</el-link>
                </div>
            </el-upload>
            <div slot="footer" class="dialog-footer">
                <el-button @click="upload.open = false" icon="el-icon-close" size="small">取 消</el-button>
                <el-button type="primary" @click="submitFileForm" icon="el-icon-check" size="small">确 定</el-button>
            </div>
        </el-dialog>
        <!-- 导入对话框 -->
        <import-dialog :visible.sync="uerGroupVisible" @callback="uploadCallback" :action="'/ny-iqc/uerGroup/import'" :templateUrl="'/static/UerGroup.xlsx'" />
    </div>
</template>
<script>
import {
    listPost,
    getPost,
    delPost,
    addPost,
    updatePost,
} from '@/api/system/post'
import {
    listUerGroup,
    addQmsUser,
    delUerGroup,
    importManagement,
} from '@/api/system/userGroup'
import { getToken } from '@/utils/auth'
import Detail from './detail'
import Drawer from './drawer'
import EnjoyUserTreeDialog from '@/components/EnjoyUserTreeDialog'
import importDialog from '../../components/importDialog'
export default {
    name: 'UserGroup',
    dicts: ['sys_normal_disable'],
    components: { Detail, Drawer, EnjoyUserTreeDialog, importDialog },
    data() {
        return {
            dialogType: 1, //1:新增  2：编辑 3：查看
            detailVisible: false,
            drawerVisible: false,
            userDialogVisible: false,
            userDialogId: undefined,
            uerGroupVisible: false,
            // 遮罩层
            loading: true,
            // 导出遮罩层
            exportLoading: false,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 岗位表格数据
            postList: [],
            // 弹出层标题
            title: '',
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                groupName: '',
                factoryName: '',
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                postName: [
                    {
                        required: true,
                        message: '岗位名称不能为空',
                        trigger: 'blur',
                    },
                ],
                postCode: [
                    {
                        required: true,
                        message: '岗位编码不能为空',
                        trigger: 'blur',
                    },
                ],
                postSort: [
                    {
                        required: true,
                        message: '岗位顺序不能为空',
                        trigger: 'blur',
                    },
                ],
            },
            fullscreen: false,
            currentCheckData: [],
            upload: {
                // 是否显示弹出层（用户导入）
                open: false,
                // 弹出层标题（用户导入）
                title: '',
                // 是否禁用上传
                isUploading: false,
                // 是否更新已经存在的用户数据
                updateSupport: 0,
                // 设置上传的请求头部
                headers: { Authorization: 'Bearer ' + getToken() },
                // 上传的地址
                url: process.env.VUE_APP_BASE_API + '/ny-iqc/uerGroup/import',
            },
            names: [],
        }
    },
    created() {
        this.getList()
    },
    methods: {
        /** 查询岗位列表 */
        getList() {
            this.loading = true
            listUerGroup(this.queryParams).then((response) => {
                this.postList = response.rows
                this.total = response.total
                this.loading = false
            })
        },
        uploadCallback() {
            this.getList()
        },
        // 取消按钮
        cancel() {
            this.open = false
            this.reset()
        },
        // 表单重置
        reset() {
            this.form = {
                postId: undefined,
                postCode: undefined,
                postName: undefined,
                postSort: 0,
                status: '0',
                remark: undefined,
            }
            this.resetForm('form')
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm('queryForm')
            this.handleQuery()
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.currentCheckData = selection
            this.ids = selection.map((item) => item.id)
            this.names = selection.map((item) => item.groupName)
            this.single = selection.length != 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset()
            this.dialogType = 1
            this.detailVisible = true
        },
        // 编辑按钮操作
        handleEdit() {
            if (!this.currentCheckData.length) {
                this.$message.error('请勾选用户组！')
                return
            }
            if (this.currentCheckData.length === 1) {
                this.dialogType = 2
                this.detailVisible = true
                this.form = this.currentCheckData[0]
            } else {
                this.$message.error('只能勾选一条用户组！')
            }
        },
        /** 添加用户操作 */
        handleUpdate(row) {
            this.reset()
            // this.userDialogVisible = true
            // this.userDialogId = row.id

            this.$router.push('/system/usergroupadd?id=' + row.id)
            // this.$router.push('/login')
        },
        /** 提交按钮 */
        submitForm: function () {
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    if (this.form.postId != undefined) {
                        updatePost(this.form).then((response) => {
                            this.$modal.msgSuccess(this.$t('formValidation.successfullyModified'))
                            this.open = false
                            this.getList()
                        })
                    } else {
                        addPost(this.form).then((response) => {
                            this.$modal.msgSuccess('新增成功')
                            this.open = false
                            this.getList()
                        })
                    }
                }
            })
        },
        handleView(row, type) {
            this.drawerVisible = true
            this.dialogType = type
            this.form = row
        },
        handleRemove() {
            if (!this.currentCheckData.length) {
                this.$modal.msgWarning('请勾选用户组!')
                return
            }
            this.handleDelete()
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = (row && row.id) || this.ids
            const names = (row && row.groupName) || this.names
            this.$modal
                .confirm('是否确认删除用户组名为"' + names + '"的数据项？')
                .then(function () {
                    return delUerGroup(ids)
                })
                .then(() => {
                    this.getList()
                    this.$modal.msgSuccess(this.$t('deptManage.delSuc'))
                })
                .catch(() => {})
        },
        /** 下载模板操作 */
        importTemplate() {
            this.download(
                'system/saas/user/importTemplate',
                {},
                `user_template_${new Date().getTime()}.xlsx`
            )
        },
        // 文件上传中处理
        handleFileUploadProgress(event, file, fileList) {
            this.upload.isUploading = true
        },
        // 文件上传成功处理
        handleFileSuccess(response, file, fileList) {
            this.upload.open = false
            this.upload.isUploading = false
            this.$refs.upload.clearFiles()
            this.$modal.msgSuccess(this.$t('formErrMsg.importantSuccess'))
            this.getList()
        },

        // 提交上传文件
        submitFileForm() {
            this.$refs.upload.submit()
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download(
                'ny-iqc/uerGroup/export',
                {
                    ...this.queryParams,
                },
                `UerGroup_${new Date().getTime()}.xlsx`
            )
        },
        handleImport() {
            this.uerGroupVisible = true
        },
        handlerDialogChange(e) {
            addQmsUser(
                e.map((i) => {
                    return {
                        deptId: e.deptId,
                        deptName: i.deptName,
                        groupId: this.userDialogId,
                        userId: i.userId,
                        userName: i.userName,
                    }
                })
            ).then((res) => {
                if (res.code == 200) {
                    this.$message.success(this.$t('formValidation.addedSuccessfully'))
                }
            })
        },
        async handleClick(e) {
            console.log('22222', e)
            try {
                const formData = new FormData()
                formData.append('file', e.target.files[0])
                const res = await importManagement(formData)
                if (res.code == 200) {
                    this.$message.success('导入成功')
                    this.getList()
                    this.$refs['excel-upload-input'].value = ''
                }
            } catch (error) {
                this.$refs['excel-upload-input'].value = ''
            }
        },
    },
}
</script>
